#include "AbstractSocket.h"
#include <unistd.h>
#include <string>
#include <cstring>
#include <cerrno>
#include <iostream>
#include <sstream>

using namespace std;

AbstractSocket::AbstractSocket(int fd):
    _socket_fd(fd)
{}

AbstractSocket::AbstractSocket(string rem_ip, int rem_port, string local_ip, int local_port, int fd):
    iostream(),
    _ip(rem_ip),
    _port(rem_port),
    _local_ip(local_ip),
    _local_port(local_port),
    _socket_fd(fd)
{}


bool  AbstractSocket::close()
{
    if (::close(_socket_fd) !=0){
        stringstream strstr;
        strstr << "\n--------------------------------------\n "
               << "\t Error closing socket fd "
               << _socket_fd
               << "\n"
               << "\t Error number "
               << errno
               << ": "
               << strerror(errno)
               << "\n--------------------------------------\n "
                  ;
        cout << (strstr.str().c_str());
        return false;
    }
    return true;
}

AbstractSocket& AbstractSocket::operator <<(const string & cad) throw (char const*)
{
    try{
        this->write(cad,10);
    }catch(char const* e){
        throw e;
    }

    return *this;

}

AbstractSocket& AbstractSocket::operator <<(char const* cad) throw (char const *)
{
    try{
        string st = cad;
        this->write(st,10);
    }catch(char const* e){
        throw e;
    }

    return *this;

}

AbstractSocket& AbstractSocket::operator >>(string & cad) throw (char const *)
{
    try{
        cad = this->read();
    }catch(char const* e){
        throw e;
    }
}
